<template>
  <div class="editor-wrap">
    <div class="editor-head">
      <input
        type="text"
        placeholder="输入文章标题..."
        class="title-input"
        v-model="ajaxSend.articleTitle"
      >
      <div class="right-box">
        <div class="right-draft">
          <span>{{this.draftInfo}}</span>
          <router-link to="/draft">草稿</router-link>
        </div>
        <div class="index-box">
          <router-link to="/">回到首页</router-link>
        </div>
        <div class="send-poup">
          <div class="toggle-btn" @click="sendBoxToggle">
            <span class="title">{{this.isUpdate?'更新':'发布'}}</span>
            <i class="iconfont" :class="{'arrow-up': this.sendContent.sendBox, 'arrow-down': !this.sendContent.sendBox}"></i>
          </div>
          <div class="send-content" v-if="this.sendContent.sendBox">
            <div class="title">{{this.isUpdate?'更新文章':'发布文章'}}</div>
            <div class="category-box">
              <div class="category-title">选择分类</div>
              <ul class="category-list">
                <li
                  class="item"
                  v-for="item in this.ajaxReceive.firstModule"
                  :key="item.id"
                  :class="{active: ajaxSend.firstModuleIndex === item.id}"
                  @click="changeFirstModuleIndex(item.id)"
                >
                  {{item.module_name}}
                </li>
              </ul>
            </div>
            <div class="tag-box">
              <div class="category-title">标签</div>
              <ul class="category-list">
                <li
                  class="item"
                  v-for="(item,key) of this.ajaxSend.tagList"
                  :key = "key"
                  @click="deleteTag(key)"
                >
                  {{item.module_name}}
                </li>
              </ul>
              <div class="tag-input">
                <input
                  type="text"
                  placeholder="搜索标签（选填）"
                  class="input"
                  v-model="sendContent.tagInput"
                >
                <ul class="tag-list" v-if="this.ajaxReceive.tagSerach.length">
                  <li
                    class="tag"
                    v-for="(item,key) of this.ajaxReceive.tagSerach"
                    :key="key"
                    @click="addTag(key)"
                  >
                    {{item.module_name}}
                  </li>
                </ul>
              </div>
            </div>
            <button class="publish-btn" @click="publish">
              {{this.isUpdate?'确认并更新':'确认并发布'}}
            </button>
            <!-- <button class="publish-btn" @click="publish" v-else>
              确认并发布
            </button> -->
          </div>
        </div>
      </div>
    </div>
    <div class="editor-content">
      <textarea ref="editormd"></textarea>
    </div>
    <div class="draft-box">
      <span>{{this.draftInfo}}</span>
      <router-link to="/draft">草稿</router-link>
    </div>
    <div class="goHome">
      <router-link to="/">回到首页</router-link>
    </div>
    <div ref="error"></div>
  </div>
</template>

<script>
import SimpleMDE from 'simplemde'
export default {
  name: '',
  data () {
    return {
      draftInfo: '文章将会自动保存至',
      isUpdate: false,
      sendContent: {
        sendBox: false, // 控制发送框的显示
        tagInput: '', // 绑定搜索标签输入框的内容
        tagInputTimer: null // 标签输入框变动向服务器请求数据时的间隔
      },
      ajaxSend: {
        articleTitle: '', // 文章标题
        tagList: [], // 添加的二级目录标签
        firstModuleIndex: '7' // 所属一级目录
      },
      ajaxReceive: {
        tagSerach: [],
        firstModule: []
      }
    }
  },
  methods: {
    initContent (res, _this) {
      console.log(res)
      console.log(_this)
      _this.ajaxSend.articleTitle = res.dataInfo.title
      _this.simplemde.value(res.dataInfo.content)
      _this.ajaxSend.firstModuleIndex = res.dataInfo.first_module
      _this.ajaxSend.tagList = res.dataInfo.second_module
    },
    contentChange (_this) {
      console.log(_this.simplemde.value())
    },
    sendBoxToggle () {
      this.sendContent.sendBox = !this.sendContent.sendBox
    },
    changeFirstModuleIndex (index) {
      this.ajaxSend.firstModuleIndex = index
    },
    deleteTag (index) {
      this.ajaxSend.tagList.splice(index, 1)
    },
    addTag (index) {
      // console.log(index)
      for (let item in this.ajaxSend.tagList) {
        if (this.ajaxSend.tagList[item].id === this.ajaxReceive.tagSerach[index].id) {
          this.common.showRegError('此标签已添加，请勿重复添加', this)
          return false
        }
      }
      if (this.ajaxSend.tagList.length >= 4) {
        this.common.showRegError('每篇文章最多添加四个标签', this)
        return false
      }
      this.ajaxSend.tagList.push(this.ajaxReceive.tagSerach[index])
      this.ajaxReceive.tagSerach = []
      this.sendContent.tagInput = ''
    },
    publish () {
      if (this.ajaxSend.articleTitle.replace(/(^\s*)|(\s*$)/g, '') === '') {
        this.common.showRegError('标题不能为空', this)
        return false
      }
      if (this.simplemde.value().replace(/(^\s*)|(\s*$)/g, '') === '') {
        this.common.showRegError('文章内容不能为空', this)
        return false
      }
      let taglist = []
      if (this.ajaxSend.tagList.length === 0) {
        this.common.showRegError('至少选择一个标签', this)
        return false
      }
      for (let i in this.ajaxSend.tagList) {
        taglist[i] = this.ajaxSend.tagList[i].id
      }
      this.$ajax({
        method: 'post',
        url: '/web/php/publish.php',
        data: this.$qs.stringify({
          type: 'publish',
          title: this.ajaxSend.articleTitle,
          content: this.simplemde.value(),
          firstModule: this.ajaxSend.firstModuleIndex,
          secondModule: taglist,
          articleId: this.$route.params.id || ''
        })
      }).then((res) => {
        res = res.data
        switch (res.returnCode) {
          case 10060: // 文章发布成功
            this.$router.push('/article/published/')
            break
          case 10061:
            this.common.showRegError('标题不能为空', this)
            break
          case 10062:
            this.common.showRegError('内容不能为空', this)
            break
          case 10064:
            this.common.showRegError('至少选择一个标签', this)
            break
          case 10070:
            this.common.showRegError('文章更新成功', this, true)
            this.$router.push('/article/' + res.dataInfo.articleId)
            break
          case 10071:
            this.common.showRegError('作者验证失败，您没有权限编辑本文章', this)
            break
          case 10040:
            this.common.showRegError('没有检测到登录信息，请登录后重试', this)
            break
        }
      })
    }
  },
  beforeCreate () {
    document.getElementsByClassName('header-wrap')[0].style.display = 'none'
  },
  mounted () {
    /** 初始化编辑器 */
    this.simplemde = new SimpleMDE({
      autoDownloadFontAwesome: false,
      renderingConfig: {
        codeSyntaxHighlighting: true
      },
      toolbar: [
        'bold',
        'italic',
        'strikethrough',
        'heading',
        // 'heading-smaller',
        // 'heading-bigger',
        // 'heading-1',
        // 'heading-2',
        // 'heading-3',
        '|',
        'code',
        'quote',
        'unordered-list',
        'ordered-list',
        '|',
        'link',
        'image',
        'table',
        'horizontal-rule',
        '|',
        'preview',
        'side-by-side',
        'fullscreen',
        'clean-block',
        'guide'
      ]
    })
    /** 判断是否是更新文章 */
    if (this.$route.name === 'updateArticle') {
      this.isUpdate = true
      // console.log(this)
      this.$ajax({
        method: 'post',
        url: '/web/php/article.php',
        data: this.$qs.stringify({
          type: 'get_article',
          articleId: this.$route.params.id
        })
      }).then((res) => {
        res = res.data
        switch (res.returnCode) {
          case 10080:
            if (!res.dataInfo.isAuthor) {
              this.common.showRegError('作者信息验证错误，您没有权限编辑本文章', this)
              this.$router.push('/')
            }
            this.$options.methods.initContent(res, this)
            break
          case 10081:
            this.$router.push('/')
            this.common.showRegError(res.dataInfo, this)
            break
          default:
            this.$router.push('/')
            this.common.showRegError('参数错误，同学你不要调皮哦', this)
            break
        }
      })
    }
    /** 获取所有一级目录 */
    this.$ajax({
      method: 'post',
      url: '/web/php/inc/module.php',
      data: this.$qs.stringify({
        type: 'get_first_module'
      })
    }).then((res) => {
      res = res.data
      if (res.state === 'ok') {
        this.ajaxReceive.firstModule = res.module
      }
    })
    this.simplemde.codemirror.on('change', () => {
      this.$options.methods.contentChange(this)
    })
  },
  destroyed () {
    document.getElementsByClassName('header-wrap')[0].style.display = 'block'
  },
  watch: {
    tagInputValue () {
      clearTimeout(this.sendContent.tagInputTimer)
      this.sendContent.tagInputTimer = setTimeout(() => {
        if (this.sendContent.tagInput.replace(/(^\s*)|(\s*$)/g, '') === '') {
          this.ajaxReceive.tagSerach = []
          return false
        }
        this.$ajax({
          method: 'post',
          url: '/web/php/inc/module.php',
          data: this.$qs.stringify({
            type: 'get_module',
            module_name: this.sendContent.tagInput
          })
        }).then((res) => {
          res = res.data
          if (res.state === 'ok') {
            this.ajaxReceive.tagSerach = res.module
          }
        })
      }, 600)
    }
  },
  computed: {
    tagInputValue () {
      return this.sendContent.tagInput
    }
  }
}

</script>
<style lang='stylus'>
@import '~styles/varibles'
// 编辑器滚动条样式
.CodeMirror-vscrollbar
  display none!important
.CodeMirror-sizer
  padding 0!important
.CodeMirror-scroll
  margin 0
  overflow auto!important
  padding .3rem 0 10rem .3rem
  box-sizing border-box
  &::-webkit-scrollbar
    width:5px;
    background:transparentify/* 整个滚条背景 */
  &::-webkit-scrollbar-thumb
    -webkit-border-radius:4px;
    border-radius:4px;
    background: #c1c1c1; /* 滚条内嵌颜色 */
.editor-preview-side
  &::-webkit-scrollbar
    width:5px;
    background:transparentify/* 整个滚条背景 */
  &::-webkit-scrollbar-thumb
    -webkit-border-radius:4px;
    border-radius:4px;
    background: #c1c1c1; /* 滚条内嵌颜色 */

.editor-wrap
  position fixed
  top 0
  left 0
  right 0
  bottom 0
  .editor-head
    display flex
    background #fff
    height 1.2rem
    align-items center
    padding 0 .32rem
    position relative
    .title-input
      font-size .48rem
      font-weight bold
      flex 1
      min-width 2rem
    .right-box
      flex-shrink 0
      user-select none
      display flex
      .send-poup
        position relative
        .toggle-btn
          font-size .32rem
          color $theme-color
          cursor pointer
          .iconfont
            font-size .28rem
          .arrow-down:before
            content '\e617'
          .arrow-up:before
            transform rotateX(180deg)
            content '\e617'
            display inline-block
        .send-content
          width 5.72rem
          position absolute
          top .76rem
          right -.44rem
          z-index 999
          padding .48rem
          border 1px  solid #ddd
          background #fff
          color $theme-3-color
          &:before
            content ''
            position absolute
            width .2rem
            height .2rem
            top -0.12rem
            right 1.1rem
            transform rotateZ(-45deg)
            background #ffffff
            border-top 1px solid #ddd
            border-right 1px solid #ddd
          .title
            font-weight bold
            font-size .38rem
            margin-bottom .36rem
          .category-box,.tag-box
            margin-bottom .24rem
            .category-title
              margin-bottom .24rem
              font-size .32rem
            .category-list
              display flex
              flex-wrap wrap
              .item
                border 1px solid #f1f1f1
                margin 0 .14rem .19rem 0
                padding .1rem .17rem
                cursor pointer
                border-radius .02rem
                font-size .26rem
                &:hover,&.active
                  color $theme-color
                  background-color rgba(0,127,255,.15)
                  border-color rgba(0,127,255,.15)
          .tag-box
            .tag-input
              position relative
              .input
                border-bottom .02rem solid #ddd
                width 100%
                &::-webkit-input-placeholder
                  color #ddd
            .tag-list
              position absolute
              border .02rem solid #ddd
              width 3.8rem
              background #fff
              padding .14rem 0
              border-top 0
              .tag
                padding .14rem .24rem
                cursor pointer
                &:hover
                  color $theme-color
          .publish-btn
            display block
            margin auto
            border none
            color $theme-color
            background $theme-background
            border .02rem solid $theme-color
            padding .10rem .36rem
            cursor pointer
            &:hover
              background #f0f7ff
      .right-draft
        font-size .32rem
        color $theme-5-color
        margin-right .6rem
        &>a
          color $theme-5-color
          border .02rem solid $theme-5-color
          padding .06rem .12rem
          border-radius .04rem
          &:hover
            color $theme-3-color
            border-color $theme-3-color
      .index-box
        margin-right .6rem
        &>a
          color $theme-5-color
          font-size .32rem
          border-bottom .02rem solid $theme-5-color
          &:hover
            color $theme-2-color
  .editor-content
    position: absolute;
    top: 1.2rem;
    bottom: 0;
    left: 0;
    right: 0;
    .editor-toolbar // 编辑器工具栏
      position absolute
      top -0.02rem
      width 100%
      box-sizing border-box
      border-bottom none
      display flex
      height 1rem
      align-items center
      z-index 111
      border 1px solid #ddd
      overflow-x auto
      &.fullscreen
        top 1.18rem
        position fixed
        padding 0 .3rem
        border 1px solid #ddd
      &>a
        flex-shrink 0
    .CodeMirror // 编辑器输入框
      background #f8f9fa
      padding 0
      position: absolute;
      top: 0.98rem;
      left: 0;
      right: 0;
      bottom: 0;
      &::-webkit-scrollbar
        width:5px;
        background:rgb(196, 196, 196); /* 整个滚条背景 */
      &.CodeMirror-fullscreen
        top 2.18rem
        box-sizing: border-box;
    .editor-preview-side //编辑器侧边栏
      font-family 'Microsoft YaHei'
      word-wrap break-word
      &.editor-preview-active-side
        top 2.18rem
    .editor-statusbar // 编辑器底部字数统计
      position absolute
      right: 0
      bottom: 0
      z-index: 10
  .draft-box
    position fixed
    bottom .2rem
    left .2rem
    z-index 110
    color $theme-3-color
    display none
    flex-direction column
    justify-content center
    &>a
      padding .10rem 0
      border .02rem solid $theme-4-color
      width 1.4rem
      text-align center
      margin .16rem auto 0
  .goHome
    position fixed
    z-index 110
    right .5rem
    bottom .76rem
    border .02rem solid $theme-color
    padding .14rem .28rem
    display none
    &>a
      color $theme-color
      &:after
        position absolute
        content ''
        top 0
        right 0
        left 0
        bottom 0
        background rgba(255,255,255,.5)
        z-index -1

@media only screen and (max-width: 980px)
  .editor-wrap .editor-head .right-box
    .index-box,.right-draft
      display none
  .editor-wrap
    .goHome
      display block
    .draft-box
      display flex
</style>
